import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyrefresh/bezier_bounce_footer.dart';
import 'package:flutter_easyrefresh/bezier_circle_header.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanchong/app/store/search.dart';
import 'package:wanchong/conf.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:wanchong/widget/store_item.dart';

class SearchResult extends StatefulWidget {
  final String keywords;
  SearchResult({Key key, this.keywords});
  @override
  _SearchResultState createState() => _SearchResultState();
}

class SortCondition {
  String name;
  bool isSelected;

  SortCondition({this.name, this.isSelected});
}

class _SearchResultState extends State<SearchResult> {
  GlobalKey<EasyRefreshState> _easyRefreshKey =
      new GlobalKey<EasyRefreshState>();
  GlobalKey<RefreshHeaderState> _headerKey =
      new GlobalKey<RefreshHeaderState>();
  GlobalKey<RefreshFooterState> _footerKey =
      new GlobalKey<RefreshFooterState>();
  TextEditingController _controller = TextEditingController();
  GlobalKey _stackKey = GlobalKey();
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  List<SortCondition> _brandSortConditions = [];
  List<SortCondition> _distanceSortConditions = [];
  SortCondition _selectBrandSortCondition;
  SortCondition _selectDistanceSortCondition;
  @override
  void initState() {
    super.initState();
    _brandSortConditions.add(SortCondition(name: '全部', isSelected: true));
    _brandSortConditions.add(SortCondition(name: '金逸影城', isSelected: false));
    _brandSortConditions
        .add(SortCondition(name: '中影国际城我比较长，你看我选择后是怎么显示的', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '星美国际城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '博纳国际城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '大地影院', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '嘉禾影城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '太平洋影城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城1', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城2', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城3', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城4', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城5', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城6', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城7', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城8', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城9', isSelected: false));
    _distanceSortConditions.add(SortCondition(name: '距离近', isSelected: true));
    _distanceSortConditions.add(SortCondition(name: '价格低', isSelected: false));
    _selectBrandSortCondition = _brandSortConditions[0];
    _selectDistanceSortCondition = _distanceSortConditions[0];
    _controller.text = widget.keywords;
    // _controller.addListener(listener)
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        elevation: 0.0,
        title: Row(
          children: <Widget>[
            GestureDetector(
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (BuildContext context) => Search()));
              },
              child: Container(
                // width: 30.0,
                height: double.infinity,
                color: Colors.transparent,
                child: Icon(
                  Icons.chevron_left,
                  size: 26.0,
                ),
                padding: EdgeInsets.only(right: 5.0),
              ),
            ),
            Expanded(
              child: GestureDetector(
                onTap: () {
                  print("object");
                },
                child: Center(
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.only(
                      top: ScreenUtil.getInstance().setHeight(10.0),
                      bottom: ScreenUtil.getInstance().setHeight(10.0),
                      left: ScreenUtil.getInstance().setWidth(16.0),
                    ),
                    decoration: BoxDecoration(
                      color: Color(0xFFFAFAFA),
                      borderRadius: BorderRadius.circular(5.0),
                    ),
                    child: Text(
                      widget.keywords,
                      style: TextStyle(
                        fontSize: ScreenUtil.getInstance().setSp(14.0),
                        color: Color(MainColor),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      body: Stack(
        key: _stackKey,
        children: <Widget>[
          Column(
            children: <Widget>[
              GZXDropDownHeader(
                stackKey: _stackKey,
                items: [
                  GZXDropDownHeaderItem("间隔距离"),
                  GZXDropDownHeaderItem("门店类型"),
                  GZXDropDownHeaderItem("门店类型"),
                  GZXDropDownHeaderItem("优惠力度"),
                ],
                controller: _dropdownMenuController,
                borderWidth: 0.0,
                iconColor: Color(0xFF647280),
                style: TextStyle(
                  color: Color(0xFF647280),
                  fontSize: 12.0,
                ),
                dropDownStyle: TextStyle(
                  fontSize: 12,
                  color: Color(0xFF647280),
                ),
              ),
              _list()
            ],
          ),
          GZXDropDownMenu(
            // controller用于控制menu的显示或隐藏
            controller: _dropdownMenuController,
            // 下拉菜单显示或隐藏动画时长
            animationMilliseconds: 300,
            menus: [
              GZXDropdownMenuBuilder(
                  dropDownHeight: 40 * 8.0,
                  dropDownWidget:
                      _buildConditionListWidget(_brandSortConditions, (value) {
                    _selectBrandSortCondition = value;
                    // _dropDownHeaderItemStrings[1] =
                    //     _selectBrandSortCondition.name == '全部' ? '品牌' : _selectBrandSortCondition.name;
                    _dropdownMenuController.hide();
                    setState(() {});
                  })),
              GZXDropdownMenuBuilder(
                  dropDownHeight: 40 * 8.0,
                  dropDownWidget:
                      _buildConditionListWidget(_brandSortConditions, (value) {
                    _selectBrandSortCondition = value;
                    // _dropDownHeaderItemStrings[1] =
                    //     _selectBrandSortCondition.name == '全部' ? '品牌' : _selectBrandSortCondition.name;
                    _dropdownMenuController.hide();
                    setState(() {});
                  })),
              GZXDropdownMenuBuilder(
                  dropDownHeight: 40 * 8.0,
                  dropDownWidget:
                      _buildConditionListWidget(_brandSortConditions, (value) {
                    _selectBrandSortCondition = value;
                    // _dropDownHeaderItemStrings[1] =
                    //     _selectBrandSortCondition.name == '全部' ? '品牌' : _selectBrandSortCondition.name;
                    _dropdownMenuController.hide();
                    setState(() {});
                  })),
            ],
          ),
        ],
      ),
    );
  }

  Widget _list() {
    return Expanded(
      child: Center(
        child: EasyRefresh(
          key: _easyRefreshKey,
          behavior: ScrollOverBehavior(),
          refreshHeader: BezierCircleHeader(
            key: _headerKey,
            backgroundColor: Color(0xFFFFCC33),
          ),
          refreshFooter: BezierBounceFooter(
            key: _footerKey,
            backgroundColor: Color(0xFFFFCC33),
          ),
          onRefresh: () async {
            await new Future.delayed(const Duration(seconds: 1), () {
              setState(() {
                // str.clear();
                // str.addAll(addStr);
              });
            });
          },
          loadMore: () async {
            await new Future.delayed(const Duration(seconds: 1), () {
              // if (str.length < 20) {
              //   setState(() {
              //     str.addAll(addStr);
              //   });
              // }
            });
          },
          child: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return StoreItem(
                storeImg: CachedNetworkImage(imageUrl: "http://b-ssl.duitang.com/uploads/item/201503/04/20150304121513_c5LEa.jpeg",fit: BoxFit.cover,),
                storeName: "其齐鲁宠物店",
                addr: "北京",
                addrName: "九方购物中心",
                catName: "宠物医院",
                tags: List.generate(6, (index)=>"标签$index"),
                distance: index*30.0,
              );
            },
            itemCount: 50,
          ),
        ),
      ),
    );
  }

  Widget _buildConditionListWidget(items, void itemOnTap(sortCondition)) {
    return ListView.separated(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) =>
          Divider(height: 1.0),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        SortCondition goodsSortCondition = items[index];
        return GestureDetector(
          onTap: () {
            for (var value in items) {
              value.isSelected = false;
            }
            goodsSortCondition.isSelected = true;

            itemOnTap(goodsSortCondition);
          },
          child: Container(
//            color: Colors.blue,
            height: 40,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: Text(
                    goodsSortCondition.name,
                    style: TextStyle(
                      color: goodsSortCondition.isSelected
                          ? Theme.of(context).primaryColor
                          : Colors.black,
                    ),
                  ),
                ),
                goodsSortCondition.isSelected
                    ? Icon(
                        Icons.check,
                        color: Theme.of(context).primaryColor,
                        size: 16,
                      )
                    : SizedBox(),
                SizedBox(
                  width: 16,
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
